package org.ricks.rpc.asm;

import java.io.*;
import java.nio.ByteBuffer;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;

// 2. 协议编解码（Lambda优化）
public class RpcCodec {
    public static final BiFunction<ByteBuffer, Class<?>, Object> DEFAULT_DECODER =
            (buffer, type) -> {
                try {
                    int length = buffer.getInt();
                    byte[] bytes = new byte[length];
                    buffer.get(bytes);
                    return new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
                } catch (Exception e) {
                    throw new RuntimeException("Decode failed", e);
                }
            };

    public static final BiConsumer<Object, ByteBuffer> DEFAULT_ENCODER =
            (obj, buffer) -> {
                try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                     ObjectOutputStream oos = new ObjectOutputStream(bos)) {
                    oos.writeObject(obj);
                    byte[] bytes = bos.toByteArray();
                    buffer.putInt(bytes.length);
                    buffer.put(bytes);
                } catch (IOException e) {
                    throw new RuntimeException("Encode failed", e);
                }
            };
}